//
//  THChildSelectViewController.m
//  TreeHole
//
//  Created by apple on 2020/7/27.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "THChildSelectViewController.h"
#import "THHomeCollectionViewCell.h"
@interface THChildSelectViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic, assign) NSInteger                     page;/**<  */
@property(nonatomic, strong) NSMutableArray                     *dataSouce;/**<  */
@property(nonatomic, assign) NSInteger                     index;/**<  */
@end

@implementation THChildSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.index = -1;
    [self.view addSubview:self.collectionView];
    
    __weak typeof(self) weakSelf =  self;
    self.collectionView.st_noreslutView = [[STTools_NoresultView alloc] initWithFrame:CGRectMake(0, 30, STONEOBS_UI_UISCREEN_WIDTH, 400) title:@"暂无数据" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    self.collectionView.showsVerticalScrollIndicator = NO;
    // Do any additional setup after loading the view.
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * flow = [UICollectionViewFlowLayout new];
        flow.minimumLineSpacing = 5;
        flow.minimumInteritemSpacing = 5;
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.sectionInset = UIEdgeInsetsMake(10,12 ,60, 12);
        UIScrollView * scrollView = (id)[self.parentViewController valueForKey:@"scrollView"];
        _collectionView = [[UICollectionView alloc] initWithFrame:scrollView.bounds collectionViewLayout:flow];
        _collectionView.backgroundColor = UIColor.whiteColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.alwaysBounceVertical = NO;
        //注册
        [_collectionView registerClass:[THHomeCollectionViewCell class] forCellWithReuseIdentifier:@"item"];

        self.automaticallyAdjustsScrollViewInsets = NO;
        if ([_collectionView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
                [_collectionView performSelector:@selector(setContentInsetAdjustmentBehavior:) withObject:@(2) afterDelay:0];
        }
    }
    return _collectionView;
}
#pragma --mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSouce.count;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat witdh =  (UISCREEN_WIDTH - 15 * 3)/2;
    return CGSizeMake(witdh, witdh + 60);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    THHomeCollectionViewCell * item =[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    THGoodModel * model = self.dataSouce[indexPath.row];;
    item.goodItemView.model = model;
    return item;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y < 0) {
        [scrollView setContentOffset:CGPointZero animated:0];
    }
}
#pragma --mark UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    THGoodModel * model = self.dataSouce[indexPath.row];;
    [TMUtils goto_good_detail_witdh_id:model.g_id];
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}
- (void)sendNetRequest{
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView reloadData];
}
- (void)config_table_footer{
    __weak typeof(self) weakSelf =  self;
    self.collectionView.mj_footer = [MJRefreshFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf reload_data_with_selcted_index:weakSelf.index];
    }];
    
}
- (void)reload_data_with_selcted_index:(NSInteger)index{
    self.page = 1;
    if (self.index < 0) {
        self.index = index;
    }
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    if (self.index == 0) {
        [stoneobs_net_param_dic setObject:@"1" forKey:@"is_recommend"];
        
    }
    if (self.index == 1) {
        [stoneobs_net_param_dic setObject:@"1" forKey:@"is_sr"];
        
    }
    if (self.index == 2) {
        [stoneobs_net_param_dic setObject:@"1" forKey:@"is_pt"];
        
    }
    [stoneobs_net_param_dic setObject:@(self.page) forKey:@"page"];
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/goods/goodsList"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumGet
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * dic = [responseObject valueForKey:@"data"];
        NSArray * array = dic[@"items"];
        NSArray * objArray = [THGoodModel mj_objectArrayWithKeyValuesArray:array];
        NSInteger total = [dic[@"total"] integerValue];//总数量
        CGFloat perPage = [dic[@"perPage"] floatValue];
        CGFloat allpage = total / perPage; 
        if (self.page == 1) {
            self.dataSouce = objArray.mutableCopy;
            [self.collectionView reloadData];
            if (allpage>1) {
                [self config_table_footer];
            }
        }else{
            if (self.page < allpage) {
                [self.collectionView.mj_footer endRefreshing];
            }else{
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.dataSouce addObjectsFromArray:objArray];
            [self.collectionView reloadData];
        }
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
}
@end
